package com.ruoyi.common.integrate.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.integrate.constant.WxConstant;
import com.ruoyi.common.integrate.domain.Department;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: MMDZ
 * @Date: 2022/3/24
 * @Desc:
 */
public class DemoService {

    public static void main(String[] args) {

    }

    /**
     * 递归列表
     */
    private static void recursionDeptList(List<Department> newList, List<Department> deptList) {
        for (Department dept : deptList) {
            newList.add(dept);
            if (Objects.nonNull(dept.getChildren())) {
                recursionDeptList(newList, dept.getChildren());
            }
        }
    }

    /**
     * 树形结构
     * @param departmentList
     * @return
     */
    private static List<Department> buildTree(List<Department> departmentList, Long parentId){
        Map<Long, List<Department>> collects = departmentList.stream().filter(a -> parentId != a.getParentid())
                .collect(Collectors.groupingBy(a -> a.getParentid()));
        departmentList.forEach(d -> d.setChildren(collects.get(d.getId())));
        Department department = departmentList.stream().filter(a -> parentId == a.getParentid()).findFirst().get();
        System.out.println("department = " + department);
        return departmentList.stream().filter(a -> parentId == a.getParentid()).collect(Collectors.toList());
    }

    public static List<Department> getDeptByQYWeiXin(){
        String accessToken = getAccessToken("contact_access_token", "YixfUzhqJVVbhUk05UbTrKE1o1KwjIIvheshuFtY2LE");
        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s", accessToken);
        String res = sendGet(url);
        JSONObject jsonRlt = JSON.parseObject(res);
        Integer errCode = jsonRlt.getInteger("errcode");
        List<Department> departmentList = null;
        if(0 == errCode){
            String departmentStr = jsonRlt.getString("department");
            departmentList = JSON.parseArray(departmentStr, Department.class);
        }
        return departmentList;
    }

    private static String getAccessToken(String secretKey, String secret){
        String corpid = "ww541a1d843bf8f8d7";
        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", corpid, secret);
        String res = sendGet(url);
        JSONObject jsonRlt = JSON.parseObject(res);

        Integer errCode = jsonRlt.getInteger("errcode");
        String accessToken = null;
        if(0 == errCode){
            accessToken = jsonRlt.getString("access_token");
            Integer expires = jsonRlt.getInteger("expires_in");
        }
        return accessToken;
    }

    /**
     * GET 请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：10000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
        // 创建GET请求方法实例对象
        GetMethod getMethod = new GetMethod(url);
        // 设置请求超时时间
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        getMethod.addRequestHeader("Content-Type", "application/json");
        try {
            httpClient.executeMethod(getMethod);
            String result = getMethod.getResponseBodyAsString();
            getMethod.releaseConnection();
            return result;
        } catch (IOException e) {
            System.out.println("GET请求发出失败，请求的地址为{}，错误信息为{}");
            System.out.println(e.getMessage());
        }
        return null;
    }
}
